<template lang="">
  <div></div>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN, USER_NAME, USER_INFO } from '@/store/mutation-types'
import { postAction } from '@/api/manage'
import { timeFix } from '@/utils/util'
export default {
  // inject: ["reload"],
  data() {
    return {
      dataParms: {
        code: ''
      }
    }
  },
  // 因为是在当前页面添加code的，界面没有刷新，只是添加参数，所以就必须监测路由参数的变化
  watch: {
    $route() {
      if (this.$route.query.code !== undefined) {
        this.getWeixin(this.$route.query.code, this.$route.query.state)
      }
    }
  },
  // js代码
  created() {
    this.dataParms.code = this.getUrlKey('code')
    this.getWeixin()
  },
  methods: {
    // 公共方法
    getUrlKey(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [',', ''])[1].replace(/\+/g, '%20')) || null
    },
    // 通过code获取微信信息
    getWeixin() {
      let _this = this
      // 调用接口，判断微信号是否绑定账户
      postAction('/mob/v1/check', this.dataParms).then(res => {
        if (res.code === 200) {
          // 已绑定-直接微信登录
          Vue.ls.set(ACCESS_TOKEN, res.result.token, 7 * 24 * 60 * 60 * 1000)
          Vue.ls.set(USER_NAME, res.result.userInfo.username, 7 * 24 * 60 * 60 * 1000)
          Vue.ls.set(USER_INFO, res.result.userInfo, 7 * 24 * 60 * 60 * 1000)
          this.$router.push({ path: '/dashboard/analysis' }).catch(() => {
            console.log('登录跳转首页出错,这个错误从哪里来的')
          })
          this.$notification.success({
            message: '欢迎',
            description: `${timeFix()}，欢迎回来`
          })
        } else if (res.code === 11013) {
          // 未绑定-提示信息

          this.$confirm({
            title: '提示',
            content: '该微信未绑定任何账号，立即去绑定',
            onOk() {
              _this.$router.push({ name: 'bindWx', query: { openid: res.result.openid, access_token: res.result.access_token } }).catch(() => {
                console.log('登录跳转首页出错,这个错误从哪里来的')
              })
            },
            onCancel() {
              _this.$router.push({ name: 'login' }).catch(() => {
                console.log('登录跳转首页出错,这个错误从哪里来的')
              })
            }
          })
        }
      })
    }
  }
}
</script>
